<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Airport as AirportModel;
use app\user\model\Continent as ContinentModel;
use think\facade\Cache;
use think\validate\ValidateRule;

/**
 * 城市控制器
 * @package app\user\admin
 */
class City extends Admin
{
    /**
     * 邮件发送记录日志列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data_list = ContinentModel::where($this->getMap())->where(['type'=>'city'])
            ->order($this->getOrder('id DESC'))
            ->paginate();
        if($data_list->items()){
            foreach ($data_list->items() as &$val){
                $country=ContinentModel::where(['id'=>$val['parent_id'],'type'=>'country'])->value('name');
                $val['country']=$country;
                $val['airport']=AirportModel::where(['city'=>$val['id']])->count();
            }
        }
        $btn_access = [
            'title' => 'Import',
            'icon'  => 'fa fa-fw fa-upload',
            'class' => 'btn btn-primary ajax-post confirm',
            'href'  => url('import')
        ];

        $down_access = [
            'title' => 'Download',
            'icon'  => 'fa fa-fw fa-download',
            'class' => 'btn btn-primary',
            'href'  => PUBLIC_PATH. 'static/admin/download/city.xls',
            'target'=>'_blank'
        ];

        $list_country=ContinentModel::where(['type'=>'country'])->column(['id','name']);
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('area')
            ->addTopButton('add',['title'=>'Add'])
            ->addTopButton('custom', $btn_access, ['area' => ['800px', '60%'], 'title' => ['Import', 'font-size:18px;']])
            ->addTopButton('custom',$down_access)
            ->addRightButton('edit',['title'=>'edit'])
            ->addRightButton('delete',['title'=>'delete','data-title' => 'This data is associated with __airport__ Airports. Cancel the association before deleting it','data-confirm'=>'confirm','data-cancel'=>'cancel'])
            ->addColumns([
                ['id', 'ID'],
                ['name', 'City'],
                ['country', 'Country'],
                ['airport', 'Airport'],
                ['updater', 'Updater'],
                ['update_time', 'Last update time'],
                ['right_button', 'Operation', 'btn'],
            ])
            ->setRowList($data_list)
            ->setSearchArea([
                ['text', 'name', 'City','like'],
                ['select', 'parent_id', 'Country', '', '',$list_country]
            ])
            ->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['name'] == '' && $this->error('Please fill in the City name');
            ($data['longitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Longitude or Incorrect format');
            ($data['latitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Latitude or Incorrect format');
            if(mb_strlen($data['name'])>40) $this->error('City name Up to 40 characters can be entered');
            $data['parent_id'] == '' && $this->error('Please fill in the Country');
            if(!$this->check($data['name'],$data['parent_id'])) $this->error('Data duplicated, please re-enter');
            $list = [];
            $list['name']=$data['name'];
            $list['longitude']=trim($data['longitude']);
            $list['latitude']=trim($data['latitude']);
            $list['type']='city';
            $list['parent_id']=$data['parent_id'];
            $list['update_time']=date('Y-m-d H:i:s');
            $list['create_time']=date('Y-m-d H:i:s');
            $list['updater']=session('user_auth')['username'];
            $continentModel = new ContinentModel();
            $insertID=$continentModel->insertGetId($list);
            if ($insertID) {
                //添加机场经纬度信息到redis
                $handler=Cache::store('redis')->handler();
                $handler->geoadd('ENVEE:CITY',$list['longitude'],$list['latitude'],'city_'.$insertID);
                $this->success('add success', 'index');
            } else {
                $this->error('add failed');
            }
        }
        $countries=ContinentModel::where(['type'=>'country'])->column(['id','name']);
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'City'],
                ['text', 'longitude', 'Longitude'],
                ['text', 'latitude', 'Latitude'],
                ['select','parent_id','Country','',$countries],

            ])
            ->fetch();
    }


    public function edit($id = 0)
    {
        if ($id === 0) $this->error('missing parameter');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $data['name'] == '' && $this->error('Please fill in the City name');
            if(mb_strlen($data['name'])>40) $this->error('City name Up to 40 characters can be entered');
            ($data['longitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Longitude or Incorrect format');
            ($data['latitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Latitude or Incorrect format');
            $data['parent_id'] == '' && $this->error('Please fill in the Country');
            if(!$this->check($data['name'],$data['parent_id'],$id)) $this->error('Data duplicated, please re-enter');
            $data['update_time']=date('Y-m-d H:i:s');
            $data['updater']=session('user_auth')['username'];
            if (ContinentModel::update($data,['id'=>$id])) {
                //添加机场经纬度信息到redis
                $handler=Cache::store('redis')->handler();
                $handler->geoadd(config('redis.redis_key.city_location'),trim($data['longitude']),trim($data['latitude']),'city_'.$id);
                $this->success('edit success', 'index');
            } else {
                $this->error('edit failed');
            }
        }
        // 获取数据
        $info = ContinentModel::get($id);
        $countries=ContinentModel::where(['type'=>'country'])->column(['id','name']);
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'City'],
                ['text', 'longitude', 'Longitude'],
                ['text', 'latitude', 'Latitude'],
                ['select','parent_id','Continent','',$countries],
            ])
            ->setFormData($info)
            ->fetch();
    }

    private function check($name,$parent_id,$id=0){
        $name=trim($name);
        $id=ContinentModel::where(['name'=>$name,'parent_id'=>$parent_id])
            ->when($id,function ($query)use($id){
                $query->where('id','neq',$id);
            })
            ->value('id');
        if($id){
            return false;
        }else{
            return true;
        }
    }

    public function delete($record = []){
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');

        //判断是否存在关联飞机场
        $airport=AirportModel::where(['city'=>$ids])->count();
        if($airport) $this->error('Please remove the associated airport first, and then delete');

        $handler=Cache::store('redis')->handler();
        $handler->ZREM(config('redis.redis_key.city_location'),'city_'.$ids);

        ContinentModel::where(['id'=>$ids])->delete();
        $this->success('delete success','index');
    }

    public function import(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $file_path=get_file_path($data['file']);
            if(empty($data['file'])) $this->error('please upload excel file!');
//            $ext = pathinfo($file_path);
//            //设置excel格式
//            $type = strtolower($ext["extension"]);
//            if($type=='xlsx'){
//                $type='Excel2007';
//            }elseif ($type=='csv'){
//                $type='csv';
//            }else{
//                $type='Excel5';
//            }
            require_once($_SERVER['DOCUMENT_ROOT'].'/../extend/PHPExcel/PHPExcel/IOFactory.php');
            $objPHPExcel = \PHPExcel_IOFactory::load($_SERVER['DOCUMENT_ROOT'].$file_path);
            //默认选中sheet0表
            $sheetSelected = 0;
            $objPHPExcel->setActiveSheetIndex($sheetSelected);
            //获取表格行数
            $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow();
            //获取表格列数
            $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
            $list=[];
            for ($row = 2; $row <= $rowCount; $row++) {
                $dataArr = array();
                for ($column = 'A'; $column <= $columnCount; $column++) {
                    $dataArr['name']=trim($objPHPExcel->getActiveSheet()->getCell('A' . $row)->getValue());
                    $dataArr['longitude']=trim($objPHPExcel->getActiveSheet()->getCell('B' . $row)->getValue());
                    $dataArr['latitude']=trim($objPHPExcel->getActiveSheet()->getCell('C' . $row)->getValue());
                    $dataArr['parent_name']=trim($objPHPExcel->getActiveSheet()->getCell('D' . $row)->getValue());
                }
                if(!is_numeric($dataArr['latitude']) || !is_numeric($dataArr['longitude'])){
                    $this->error('excel latitude or longitude must be number');
                }
                $list[]=$dataArr;
            }
            if($list){
                $continentModel=new ContinentModel();
                $rep=$continentModel->addAll($list,'country',session('user_auth')['username']);
                if($rep['code']==1){
                    $this->success('excel file import success','index', '_parent_reload');
                }else{
                    $this->error($rep['msg']);
                }
            }else{
                $this->error('excel file data is empty!');
            }

        }

        return ZBuilder::make('form')
            ->addFile('file', 'City File', '', '', '','xlsx,csv,xls')
            ->fetch();
    }
}
